from PyQt6.QtGui import *
from PyQt6.QtCore import *
from PyQt6.QtWidgets import *
from PyQt6.QtNetwork import *
from apply import LoginWidget
import json

class CompanyCentralWidget(QWidget):

    client = QTcpSocket()
    resizeSignal = pyqtSignal(int, int)

    def __init__(self):
        super().__init__()
        self.ifLogin = False
        self.name = ''
        self.password = ''
        self.info = ''
        self.image = QImage()
        self.client.connectToHost('localhost', 6666)
        if not self.client.waitForConnected():
            message = QMessageBox()
            message.setText("Failed to connect to server.")
            message.setWindowTitle("WRONG!")
            message.exec()
            print("Failed to connect to server.")
            exit(-1)
        else:
            print("Connected to server.")
            self.client.readyRead.connect(self.receive_messages)

        self.loginWidget = LoginWidget.login_Widget()
        self.loginWidget.tryLoginSignal.connect(self.tryLogin)

        self.layout = QVBoxLayout()
        self.layout.addWidget(self.loginWidget)
        self.setLayout(self.layout)

    def initUI(self):
        listWidget = QListWidget()

    def receive_messages(self):
        print('received')
        print('ready receive')
        datas = self.client.readAll().data().decode().split("###")

        for data in datas:
            if data == '':
                continue
            json_data = json.loads(data)
            print(data)
            if json_data[0]["message"] == 'login':
                if json_data[1]["result"] == 'success':
                    self.ifLogin = True
                else:
                    message = QMessageBox()
                    message.setText("Wrong username or wrong password")
                    message.setWindowTitle("WRONG!")
                    message.exec()
            if json_data[0]["message"] == 'data':
                name = json_data[1]["name"]
                info = json_data[1]["info"]
                image_data = QByteArray.fromBase64(json_data[1]["image"].encode())
                image = QImage.fromData(image_data)
                image.save('../ans.jpg')

        if self.ifLogin:
            self.login(self.name, self.password)


    def login(self, username, password):
        print('login')
        self.userName = self.loginWidget.getUsername()
        print('get name')
        print(self.userName)
        self.update()
        self.resizeSignal.emit(900, 560)

    def tryLogin(self, username, password):
        data = [{"message": 'login'}, {"username": username, "password": password, "type": "company"}]
        json_data = json.dumps(data)
        self.client.write(json_data.encode())
        print('send')
        self.name = username
        self.password = password

class CompanyMainWindow(QMainWindow):

    def __init__(self):
        super().__init__()

        self.setWindowTitle("审核报销信息")

        mainWidget = CompanyCentralWidget()
        mainWidget.resizeSignal.connect(self.resize)

        self.setCentralWidget(mainWidget)

if __name__ == "__main__":
    app = QApplication([])

    window = CompanyMainWindow()
    window.show()

    app.exec()